<template>
  <el-dialog v-model="props.dialogOpen" :title="props.taskTitle" destroy-on-close="true" :before-close="submitClose"
    width="50%" align-center :close-on-click-modal="false">
    <el-form ref="formRef" :model="props.dataForm.form.taskInfo" :rules="rules">
      <!-- 任务标题 -->
      <el-form-item label="任务标题" prop="title" label-width="80px">
        <el-input v-model="props.dataForm.form.taskInfo.title" autocomplete="off" maxlength="50" show-word-limit
          type="text" style="width: 200px" placeholder="请输入任务标题" />
      </el-form-item>
      <!-- 任务内容 -->
      <el-form-item label="任务内容" prop="content" label-width="80px">
        <el-input v-model="props.dataForm.form.taskInfo.content" :rows="3" maxlength="100" type="textarea" show-word-limit
          placeholder="请输入任务内容" resize="none" />
      </el-form-item>
      <!-- 上传录音 -->
      <el-form-item label="录音文件" prop="introduction" label-width="80px">
        <!-- <el-upload v-model:file-list="fileLists" class="upload-demo" :action="dataset.uploadUrl" :headers="headerObj"
            :limit="1" :on-preview="handlePreview" :on-success="handleSuccess" :on-remove="handleRemove"
            :before-upload="beforeRecordUpload" :before-remove="beforeRemove">
            <el-button type="primary">上传录音</el-button>
            <template #tip>
              <div class="el-upload__tip">
                mp3/wav文件需小于10MB.
              </div>
            </template>
          </el-upload> -->

        <el-upload v-model:file-list="recordUrl" class="upload-demo" action="#" :auto-upload="true"
          :http-request="uploadActionPDF" :before-upload="beforeUploadPDF" :before-remove="beforeRemovePDF"
          :on-change="handleChangePDF">
          <el-button icon="Download">上传文件</el-button>
          <template #tip>
            <div class="el-upload__tip">仅支持上传录音文件(一次仅可上传一条)</div>
          </template>
        </el-upload>

      </el-form-item>
      <!-- 上传图片 -->
      <el-form-item label="上传图片" label-width="80px">
        <el-upload v-model:file-list="imageUrl" action="#" list-type="picture-card" :limit="3" v-loading=loadingPhoto
          :http-request="uploadAction" :before-upload="beforeUpload" accept="image/*" :on-remove="handleRemove"
          :on-exceed="handleExceedCover">
          <el-icon>
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>

        <!-- <el-upload action="#" list-type="picture-card" :auto-upload="true" :limit="3" :on-exceed="handleExceedCover"
        :http-request="uploadAction" :before-upload="beforeUpload" accept="image/*"   :file-list="imageUrl"  >
          <el-icon>
            <Plus />
          </el-icon>

          <template #file="{ file }">
            <div>
              <img class="el-upload-list__item-thumbnail" v-for ="item in imageUrl" :src="item" alt="" />
              <span class="el-upload-list__item-actions">
                <span  class="el-upload-list__item-delete" @click="handleRemove(file)">
                  <el-icon>
                    <Delete />
                  </el-icon>
                </span>
              </span>
            </div>
          </template>
        </el-upload> -->


      <!-- 工作分类 -->
      <el-form-item label="工作分类" label-width="80px" prop="classify">
        <el-select v-model="props.dataForm.form.taskInfo.classify" placeholder="请选择你的类型">
          <el-option label="前期工作" value="0" />
          <el-option label="质量安全" value="1" />
          <el-option label="综合管理" value="2" />
          <el-option label="上级交办" value="3" />
          <el-option label="对外协调" value="4" />
          <el-option label="对上汇报" value="5" />
        </el-select>
      </el-form-item>
      <!-- 优先级 -->
      <el-form-item label="优先级" label-width="80px" prop="priority">
        <el-select v-model="props.dataForm.form.taskInfo.priority" placeholder="请选择你的类型">
          <el-option label="紧急事务(1级)" value="0" />
          <el-option label="一般事务(2级)" value="1" />
          <el-option label="待办事务(3级)" value="2" />
        </el-select>
      </el-form-item>
      <!-- 执行人 -->
      <el-form-item label="执行人" label-width="80px" prop="groupPer">
        <el-cascader ref="cascadeRef" :options="props.dataForm.options" v-model="cascadeData" collapse=true
          :show-all-levels="false" :props="pop" filterable collapse-tags collapse-tags-tooltip placeholder="请选择执行人"
          @change="changeAcademic(cascadeRef)" />
      </el-form-item>

      <!-- 时间提醒 -->
      <el-form-item label="时间提醒" label-width="80px" prop="reminderTime">
        <el-select v-model="props.dataForm.form.taskInfo.reminderTime" placeholder="请选择">
          <el-option label="1小时" value="1" />
          <el-option label="6小时" value="6" />
          <el-option label="12小时" value="12" />
          <el-option label="24小时" value="24" />
          <el-option label="3天" value="72" />
          <el-option label="7天" value="168" />
        </el-select>
      </el-form-item>
      <!-- 截止日期 -->
      <el-form-item label="截止日期" label-width="80px" prop="deadline">
        <el-date-picker v-model="props.dataForm.form.taskInfo.deadline" type="datetime" format="YYYY/MM/DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择截止日期及时间" :default-time="defaultTime" size="small" />
      </el-form-item>
    </el-form>
    <!-- 确认与取消 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="resetForm(formRef)">取消</el-button>
        <el-button type="primary" @click="submitSure(formRef)">
          确认
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>
  
<script setup>
import { fileUpload } from "../../api";
// import { groupPersons } from '../../utils/system/regroupData'
import { useList } from "../../store";

const props = defineProps({
  dataForm: {
    type: Object
  },
  taskTitle: {
    type: String
  },
  dialogOpen: {
    type: Boolean
  },
  modalTypes: {
    type: Boolean
  },


});
//使用defineEmits语法糖的方法来创建自定义事件
const emit = defineEmits(['submitClose', 'changeAcademic', 'resetForm', 'submitSure']);
let { cascadeData, imageUrl, recordUrl } = toRefs(props.dataForm)


// const imageUrl = ref([]);
const loadingPhoto = ref(false); //上传图片状态
const loadingFile = ref(false);  //上传录音文件
const store = useList()
const formRef = ref(null)   //表单ref
// 将群组数据放入执行人

//群组数据
let cascadeRef = ref(null)
const pop = reactive({
  multiple: true,
  // checkStrictly: true
})


//群组校验
const checkAge = (rule, value, callback) => {
  if (cascadeData.value == '') {
    return callback(new Error('请选择群组人员'))
  } else {
    callback()
  }
  return {}
}

const rules = {
  title: [{ required: true, message: "任务标题不能为空", trigger: "blur" }],
  classify: [{ required: true, message: "工作分类不能为空", trigger: "change" }],
  executors: [{ required: true, message: "执行人不能为空", trigger: "blur" }],
  priority: [
    { required: true, message: "优先级不能为空", trigger: "change" },
  ],
  reminderTime: [
    { required: true, message: "时间提醒不能为空", trigger: "change" },
  ],
  deadline: [{ required: true, message: "截止日期不能为空", trigger: "change" }],
  groupPer: [
    { required: true, validator: checkAge, trigger: "blur" },
    { type: 'array', message: '请选择人员' }
  ],
};

// //录音相关

//录音格式校验
const beforeUploadPDF = (file) => {
  const fileSuffix = file.name.substring(file.name.lastIndexOf(".") + 1);
  const whiteList = ["mp3", "wav", "mpeg"];

  if (whiteList.indexOf(fileSuffix) === -1) {
    ElMessage({
      message: "上传文件只能是mp3/wav/mpeg格式！",
      type: "warning",
    });
    return false;
  } else if (file.size / 1024 / 1024 > 10) {
    beforeRemovePDF2()
    ElMessage({
      message: "录音文件大小不能超过10MB！",
      type: "warning",
    });
    return false
  }
  return true;
};

//录音上传
const uploadActionPDF = (val) => {
  let param = new FormData();
  param.append("file", val.file);
  // param.append("folderName", folderName);
  fileUpload(param).then(({ data }) => {
    if (!data.data[0]) return
    if (data.code == 200) {
      props.dataForm.form.taskInfo.recordUrl = data.data
      console.log(recordUrl.value,props.dataForm.form.taskInfo.recordUrl, 'data.code');
      // recordUrl.value = data.data[0]
    }
  });
};

//附件删除
const beforeRemovePDF = (uploadFile, uploadFiles) => {
  recordUrl.value = [];
  props.dataForm.form.taskInfo.recordUrl = []
  console.log(recordUrl.value, props.dataForm.form.taskInfo.recordUrl);
  // const fileSuffix = uploadFile.name.substring(
  //   uploadFile.name.lastIndexOf(".") + 1
  // );
  // const whiteList = ["pdf", "PDF"];
  // if (whiteList.indexOf(fileSuffix) === -1) {
  //   recordUrl.value = [];
  // } else {
  //   return ElMessageBox.confirm(`确定删除${uploadFile.name} ?`).then(
  //     () => {
  //       form.value.fileIds = [];
  //       return true;
  //     },
  //     () => false
  //   );
  // }
};

const handleChangePDF = (file, fileList) => {
  if (fileList.length > 1) {
    fileList.splice(0, 1);
  }
};
// //录音上传成功
// const handleSuccess = (
//   response,
//   file
// ) => {
//   if (response.code == 200) {
//     form.value.recordUrl = response.data
//     form.value.files.push(...response.data)
//     console.log(response, 'response')
//   } else {
//     ElMessage.error({
//       message: '录音上传失败!',
//       type: 'error'
//     })
//   }
// }
// const handleRemoves = (file, uploadFiles) => {
//   console.log(file, uploadFiles)
// }
// // const beforeRemove = (uploadFile, uploadFiles) => {
// //   return ElMessageBox.confirm(
// //     `Cancel the transfert of ${uploadFile.name} ?`
// //   ).then(
// //     () => true,
// //     () => false
// //   )
// // }

// 图片相关
// // const fileList = ref([])
// const dataset = reactive({
//   uploadUrl: 'http://192.168.2.20:7011//task/uploadImage',
//   showBtnDealImg: true,
//   noneBtnImg: false,
// })
// //上传图片录音时请求头中放token
// const headerObj = reactive({
//   Authorization: localStorage.getItem('Authorization')
// })

//封面接口
const uploadAction = (val) => {
  let param = new FormData();
  param.append("file", val.file);
  loadingFile.value = true // 上传时显示上传中的状态(loading)
  fileUpload(param).then(({ data }) => {
    if (data.code == 200) {
      console.log(data.data[0].url, 'res');
      loadingFile.value = false // 上传成功之后关闭上传中状态并提示上传成功
      props.dataForm.form.taskInfo.imageUrl.push(data.data[0])
      if (!data.data[0].url) return

      //  fileList = data.data.map(item=>{
      //    return {
      //       name:item.name,
      //       url:item.url
      //    }
      // })
      // imageUrl.value.push(fileList)
      // fileList = []

      // props.imageUrl.forEach(item => {
      //   item.url = data.data[0].url
      // });
      // console.log(imageUrl.value, props.dataForm.form.taskInfo.imageUrl, '123123');
    }
  });
};
const beforeUpload = (file) => {
  //大小小于5M
  const isLt1M = file.size / 1024 / 1024 < 5;
  if (!isLt1M) {
    ElMessage({
      message: "上传图片大小不能超过5MB！",
      type: "warning",
    });
    return false;
  }
  const fileSuffix = file.name
    .substring(file.name.lastIndexOf(".") + 1)
    .toLowerCase();
    // console.log(fileSuffix,'fileSuffix')
  const whiteList = ["png", "jpg", "jpeg"];
  if (whiteList.indexOf(fileSuffix) === -1) {
    ElMessage({
      message: "上传文件只能是图片格式！",
      type: "warning",
    });
    return false;
  }
  return true;
};

//超过限制的回调
const handleExceedCover = (files, fileList) => {
  ElMessage.error({
    message: `上传图片数量超出限制！`,
    type: 'error',
  })
}
const handleRemove = (file) => {
  props.dataForm.form.taskInfo.imageUrl = props.dataForm.form.taskInfo.imageUrl.filter(item => {
    return item.name != file.name
  })
  // console.log(imageUrl.value,props.dataForm.form.taskInfo.imageUrl);
  return true;
};

const defaultTime = new Date(2000, 1, 1, 12, 0, 0);

const submitSure = (val) => {
  emit('submitSure', val)

}
//关闭弹窗
const submitClose = () => {
  emit('submitClose')

}
//取消
const resetForm = (val) => {
  emit('resetForm', val)

}

//节点改变后拿到节点数据
const changeAcademic = (cascaderRef) => {
  emit('changeAcademic', cascaderRef)
}

</script>
  
<style scoped lang="less">
// /* 图片相关 */
.avatar-uploader .avatar {
  width: 124px;
  height: 124px;
  display: block;
}

:deep(.avatar-uploader .el-upload) {
  border: 1px dashed #ccc;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 124px;
  height: 124px;
  text-align: center;
}

.imageBox {
  position: relative;
}

.imageBox:hover {
  .imageBlack {
    display: block;
  }
}

.imageBlack {
  position: absolute;
  top: 0px;
  height: 100%;
  width: 100%;
  background: rgba(0, 0, 0, 0.5);
  z-index: 999;
  display: none;
  line-height: 100px;
  text-align: center;
}
</style>
  
  